<template>
  <div class="addOrEdit-wrapper">
    <div class="top">
      <div class="title-wrapper d-flex-sb">
        <div class="title">编辑课程</div>
        <el-button
          type="primary"
          style="background: #00ADB3; border-color: none"
          @click.native="submit"
        >确认</el-button>
      </div>
    </div>
    <div class="content">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="章节名称：" prop="chapter_title">
          <el-input v-model="ruleForm.chapter_title" placeholder="限30个字" class="el-200" />
        </el-form-item>
        <el-form-item label="章节价格：" prop="chapter_price">
          <el-input v-model="ruleForm.chapter_price" placeholder="请输入章节价格" class="el-200" />
          <span class="yuan">元</span>
        </el-form-item>
        <el-form-item label="基础销量：" prop="sale_num">
          <el-input v-model="ruleForm.sale_num" placeholder="请输入基础销量" class="el-200" />
        </el-form-item>
        <el-form-item label="封面图：" prop="chapter_video_cover">
          <el-upload
            :limit="1"
            action="http://drumhome.izhixiu.cn/common/uploadFile"
            list-type="picture-card"
            :on-success="coverSuccess"
            :on-preview="coverPreview"
            :on-remove="coverRemove"
            :file-list="coverList"
          >
            <div slot="tip" class="el-upload__tip color-red">（建议尺寸：750px*750px）</div>
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt>
          </el-dialog>
        </el-form-item>
        <el-form-item label="视频" prop="chapter_video_url">
          <el-upload
            class="upload-demo"
            action="http://drumhome.izhixiu.cn/common/uploadVideo"
            :on-success="videoSuccess"
            :on-remove="videoRemove"
            :file-list="videoList"
            accept="video/*"
          >
            <el-button type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip color-red">（建议尺寸：此处可使用16：9比例视频）</div>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { addOrEditChapterItem, getChapterDetail } from '@/api/request/chapter'
const ERR_OK = 200
const validate1 = (rule, value, callback) => {
  const pass = /^\d+(\.\d+)?$/.test(value)
  if (!pass) {
    callback(new Error('请输入有效数字'))
  } else {
    callback()
  }
}
const validate2 = (rule, value, callback) => {
  const pass = /^[0-9]\d*$/.test(value)
  if (!pass) {
    callback(new Error('请输入有效数字'))
  } else {
    callback()
  }
}
export default {
  components: {
  },
  data() {
    return {
      dialogVisible: false,
      videoList: [],
      coverList: [],
      dialogImageUrl: '',
      ruleForm: {
        chapter_id: '',
        id: '',
        chapter_size: '',
        chapter_title: '',
        chapter_price: '',
        sale_num: '',
        chapter_video_url: '',
        chapter_video_cover: '',
        osskey: ''
      },
      rules: {
        chapter_title: [
          { required: true, message: '请输入章节名称', trigger: 'blur' }
        ],
        chapter_price: [
          { trigger: 'blur', validator: validate1 }
        ],
        sale_num: [
          { trigger: 'blur', validator: validate2 }
        ],
        chapter_video_url: [
          { required: true, message: '请上传视频', trigger: 'change' }
        ],
        chapter_video_cover: [
          { required: true, message: '请上传封面图', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    if (this.$route.query.chapter_id) {
      this.ruleForm.chapter_id = this.$route.query.chapter_id
      this._getChapterDetail(this.$route.query.chapter_id)
    }
    if (this.$route.query.id) {
      this.ruleForm.id = this.$route.query.id
    }
  },
  methods: {
    submit() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this._addOrEditChapterItem(this.ruleForm)
            .then(() => {
              this.$router.back()
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          return false
        }
      })
    },
    coverSuccess(response, file, fileList) {
      if (response.code === ERR_OK) {
        this.ruleForm.chapter_video_cover = response.dest
      }
    },
    coverPreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    coverRemove(file, fileList) {
      console.log(file, fileList)
    },
    videoSuccess(response, file, fileList) {
      if (response.code === ERR_OK) {
        console.log(response)
        this.ruleForm.osskey = response.ossKey
        this.ruleForm.chapter_size = response.size
        this.ruleForm.chapter_video_url = response.dest
      }
    },
    videoRemove(file, fileList) {
      console.log(file, fileList)
    },
    // 图片、视频格式化
    addFileListItem(lsit, url) {
      const oIndex = url.lastIndexOf('/')
      const name = url.slice(oIndex + 1)
      lsit.push({ name, url })
      // return { name, url }
    },
    _addOrEditChapterItem({ chapter_id, id, chapter_size, chapter_video_url, chapter_title, chapter_price, chapter_video_cover, osskey, sale_num }) {
      return addOrEditChapterItem({ chapter_id, id, chapter_size, chapter_video_url, chapter_title, chapter_price, chapter_video_cover, osskey, sale_num })
        .then(res => {
          if (res.code === ERR_OK) {
            console.log(res)
            this.$message({
              message: res.message,
              showClose: true,
              type: 'success'
            })
            return Promise.resolve()
          }
        })
        .catch(err => {
          console.log(err)
          return Promise.reject(err)
        })
    },
    _getChapterDetail(id) {
      getChapterDetail(id)
        .then(res => {
          if (res.code === ERR_OK) {
            console.log(res)
            this.ruleForm.chapter_title = res.list.chapter_title
            this.ruleForm.chapter_price = res.list.chapter_price
            this.ruleForm.sale_num = res.list.sale_num
            this.ruleForm.chapter_video_cover = res.list.chapter_video_cover
            this.addFileListItem(this.coverList, res.list.chapter_video_cover)
            this.ruleForm.chapter_video_url = res.list.chapter_video_url
            this.addFileListItem(this.videoList, res.list.chapter_video_url)
            this.ruleForm.osskey = res.list.osskey
            this.ruleForm.chapter_size = res.list.chapter_size
            this.ruleForm.id = res.list.course_id
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/el-button.scss";
.addOrEdit-wrapper {
  padding: 20px;
  box-sizing: border-box;
  background: #fff;
  height: 100%;
  flex: 1;
  .top {
    width: 100%;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 80px;
    padding: 0 35px;
    .title-wrapper {
      width: 100%;
      display: flex;
      align-content: center;
      .title {
        height: 44px;
        line-height: 44px;
        color: rgba(68, 68, 68, 1);
        font-size: 18px;
        font-family: Roboto;
        font-weight: bold;
      }
    }
  }
  .content {
    margin-top: 30px;
    .yuan {
      position: absolute;
      top: 0;
      right: 7px;
      color: #101010 !important;
    }
  }
  .d-flex-sb {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.el-200 {
  width: 350px;
}
.color-red {
  color: red;
}
.el-form /deep/ .el-form-item__content {
  width: 350px;
}
</style>

